package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.user.dto.LoginDto;
import com.heima.user.pojo.User;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import java.util.HashMap;

@Service
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 作登录校验
     *
     * @return
     */
    @Override
    public ResponseResult loginJudgment(LoginDto loginDto) {
        //取出数据
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();

        //1.正常登录
        //1.1根据手机号比对用户信息
        if (!StringUtils.isEmpty(phone) && !StringUtils.isEmpty(password)) {
            //构造查询条件
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = getOne(queryWrapper);
            //用户不存在
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            //1.2比对密码
            String salt = user.getSalt();
            //将前端传的密码加盐处理
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((salt + password).getBytes());
            //System.out.println(md5DigestAsHex);
            //密码错误
            if (!md5DigestAsHex.equals(user.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3返回数据，jwt，user，token
            //创建用户token
            String token = AppJwtUtil.getToken(user.getId().longValue());
            //将用户敏感信息去除
            user.setPassword("");
            user.setSalt("");
            //创建map将token和user放入其中
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", user);

            return ResponseResult.okResult(map);

        } else {
            //2.游客登录
            //直接将token放进去
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
